<template>
  <div class="body">
    <el-form class="form" :model="form" ref="refForm" v-loading="loading.form">
      <el-row>
        <el-col :span="12">
          <el-form-item prop="name" :rules="[{ required: true, message: '名字不能为空' }]" label="名字"
            :label-width="fromViewCofing.label_width">
            <el-input v-model="form.name" class="inp"></el-input>
          </el-form-item>

          <el-form-item prop="cooperative_price" label="合作价格" :label-width="fromViewCofing.label_width"
            :rules="[{ required: true, message: '合作价格不能为空' }]">
            <el-input class="inp" v-model="form.cooperative_price" type="number" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item prop="weight" label="权重" :rules="[{ required: true, message: '权重不能为空' }]"
            :label-width="fromViewCofing.label_width">
            <el-input class="inp" v-model="form.weight" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item prop="weight" label="联登状态" :rules="[{ required: true, message: '联登状态不能为空' }]"
            :label-width="fromViewCofing.label_width">
            <el-radio-group v-model="form.federated_login">
              <el-radio :label="1">开启</el-radio>
              <el-radio :label="0">关闭</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item prop="hyperlink" label="H5链接" :rules="[{ required: true, message: 'H5链接不能为空' }]"
            :label-width="fromViewCofing.label_width">
            <el-input class="inp" v-model="form.hyperlink" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="图标" :label-width="fromViewCofing.label_width"
            :rules="[{ required: true, message: '图标不能为空' }]" prop="logo">
            <UploadingFile accept=".jpg,.png" :limit="1" :list-type="'picture-card'" :fileList="form.logo"
              @upload-success="(files) => handleUploadingImg('logo', files)"></UploadingFile>
          </el-form-item>

          <el-form-item :label-width="fromViewCofing.label_width" prop="time_interval"
            :rules="[{ required: true, message: '推送时间区间不能为空' }]" label="推送时间区间">
            <el-time-picker is-range format="HH:mm" size="mini" v-model="form.time_interval" range-separator="至"
              start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围">
            </el-time-picker>
          </el-form-item>

          <el-form-item label="关键词" :label-width="fromViewCofing.label_width">
            <el-input class="inp" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入关键词"
              v-model="form.keyword">
            </el-input>
          </el-form-item>

          <el-form-item prop="recommend" label="推荐语" :label-width="fromViewCofing.label_width"
            :rules="[{ required: true, message: '推荐语不能为空' }]">
            <el-input class="inp" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入推荐语"
              v-model="form.recommend">
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="日利率" :label-width="fromViewCofing.label_width">
            <el-input class="inp" v-model="form.dayrate" type="number" autocomplete="off" placeholder="">
              <template slot="append">%</template></el-input>
          </el-form-item>

          <el-form-item label="申请人数" :label-width="fromViewCofing.label_width">
            <el-input class="inp" v-model="form.applicants_num" type="number" autocomplete="off"
              placeholder=""></el-input>
          </el-form-item>

          <el-form-item label="最小可贷金额" :label-width="fromViewCofing.label_width">
            <el-input class="inp" v-model="form.loan_amount_min" type="number" autocomplete="off"
              placeholder=""></el-input>
          </el-form-item>

          <el-form-item label="最大可贷金额" :label-width="fromViewCofing.label_width">
            <el-input class="inp" v-model="form.loan_amount_max" type="number" autocomplete="off"
              placeholder=""></el-input>
          </el-form-item>

          <el-form-item label="最小期数" :label-width="fromViewCofing.label_width">
            <el-input class="inp" v-model="form.cycle_min" type="number" autocomplete="off" placeholder=""></el-input>
          </el-form-item>

          <el-form-item label="最大期数" :label-width="fromViewCofing.label_width">
            <el-input class="inp" v-model="form.cycle_max" type="number" autocomplete="off" placeholder=""></el-input>
          </el-form-item>

          <!-- <el-form-item label="屏蔽渠道" :label-width="fromViewCofing.label_width">
            <el-input class="inp" v-model="form.channel_blocking" type="textarea" autocomplete="off"
              placeholder="请输入"></el-input>
          </el-form-item> -->



          <el-form-item label="渠道条件类型" :label-width="fromViewCofing.label_width">
            <el-radio-group v-model="form.channel_restriction_type">
              <el-radio label="deny">不允许</el-radio>
              <el-radio label="allow">仅允许</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="渠道选择" :label-width="fromViewCofing.label_width">
            <el-select v-model="form.channel_ids" class="inp" multiple placeholder="请选择">
              <el-option v-for="item in channel_select" :key="item.id" :label="item.id" :value="item.id" />
            </el-select>
          </el-form-item>


        </el-col>
      </el-row>

      <div class="form_footer">
        <el-button type="success" @click="fromSubmit">提交</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import UploadingFile from "@/components/Uploading/UploadingFile.vue";
// import Uploading from "@/components/Uploading/Uploading.vue";
import {
  isNullOrEmpty,
  toEscapedJsonString,
  fromEscapedJsonString,
  assignFormParams,
} from "@/utils/common";
import {
  apiAdvertisingCreate,
  apiAdvertisingDetails,
  apiAdvertisingUpdatesingle,
  apiChannelConciseAll,
} from "@/api/apiCommon";
import { getImgUrl } from "@/api/uploading";
import { formatTimeHhMm, parseMmDdDate } from "@/utils/datetimeUtil";
export default {
  name: "Index",
  components: {
    UploadingFile,
  },
  data() {
    return {
      init_form: {
        id: 0,
        name: "",
        cooperative_price: "",
        weight: 1,
        hyperlink: "",
        logo: "",
        federated_login: 0,
        time_interval: [
          new Date(2024, 8, 5, 0, 0),
          new Date(2024, 8, 5, 23, 59),
        ],
        today_start_time: "",
        today_end_time: "",
        keyword: "",
        recommend: "",
        dayrate: "0.03",
        applicants_num: "",
        loan_amount_min: "5000",
        loan_amount_max: "200000",
        cycle_min: 3,
        cycle_max: 36,
        channel_blocking: "",
        channel_restriction_type: "deny",
        channel_ids: []
      },
      form: {},
      fromViewCofing: {
        input_width: "120px",
        label_width: "160px",
      },
      business_list: [],
      time_picker: {
        temporal_interval: [
          new Date(2024, 8, 5, 0, 0),
          new Date(2024, 8, 5, 23, 59),
        ],
      },
      loading: {
        form: false,
      },
      channel_select: []
    };
  },
  created() {
    const _this = this
    var params = this.$route.query;
    this.form = this.init_form;
    if (params.id != 0) {
      this.req_details(params.id);
    }


    apiChannelConciseAll().then((response) => {
      const result = response.data.list;
      _this.channel_select = result;
    });


    // this.uploading_img.api_uploading_img_url = getUploadingImgUrl();
    // this.uploading_img.api_uploading_video_url = getUploadingVideoUrl();
    // this.uploading_img.headers = {
    //   token: getToken(),
    // };
  },
  methods: {
    //图片展示
    AppResShow(url) {
      return getImgUrl(url);
    },
    // 图片上传成功
    handleUploadingImg(field, files) {
      console.log("图片上传成功", [field, files]);
      var form = this.form;
      form[field] = files.join(", ");
      this.form = form;
      this.$forceUpdate();
    },
    // 图片删除
    handleRemoveLogo(file) {
      var form = this.form;
      form["logo_img"] = "";
      this.form = form;
      this.$forceUpdate();
    },
    /**表单提交 */
    fromSubmit() {
      const _this = this;
      var form = this.form;
      var reqData = { ..._this.form };
      // console.log(reqData, 'reqDatareqDatareqDatareqDatareqData111111111')
      if (reqData["channel_ids"]) {
        reqData["channel_ids"] = JSON.stringify(reqData["channel_ids"]);
      }
      reqData["today_start_time"] = formatTimeHhMm(reqData["time_interval"][0]);
      reqData["today_end_time"] = formatTimeHhMm(reqData["time_interval"][1]);
      delete reqData.time_interval;

      this.$refs["refForm"].validate((valid) => {
        if (valid) {
          _this.loading_start("form");
          // console.log(reqData, 'reqDatareqDatareqDatareqDatareqData')

          var formData = {}
          formData['id'] = reqData['id'];
          formData['name'] = reqData['name'];
          formData['cooperative_price'] = reqData['cooperative_price'];
          formData['weight'] = reqData['weight'];
          formData['federated_login'] = reqData['federated_login'];
          formData['hyperlink'] = reqData['hyperlink'];
          formData['logo'] = reqData['logo'];
          formData['today_start_time'] = reqData['today_start_time'];
          formData['today_end_time'] = reqData['today_end_time'];
          formData['keyword'] = reqData['keyword'];
          formData['recommend'] = reqData['recommend'];
          formData['dayrate'] = reqData['dayrate'];
          formData['applicants_num'] = reqData['applicants_num'];
          formData['loan_cycle'] = reqData['loan_cycle'];
          formData['loan_amount'] = reqData['loan_amount'];
          formData['estimated_interest'] = reqData['estimated_interest'];
          formData['average_monthly_repayment'] = reqData['average_monthly_repayment'];
          formData['loan_amount_min'] = reqData['loan_amount_min'];
          formData['loan_amount_max'] = reqData['loan_amount_max'];
          formData['cycle_min'] = reqData['cycle_min'];
          formData['cycle_max'] = reqData['cycle_max'];
          formData['annual_interest_rate'] = reqData['annual_interest_rate'];
          formData['remark'] = reqData['remark'];
          formData['application_requirement'] = reqData['application_requirement'];
          formData['channel_blocking'] = reqData['channel_blocking'];
          formData['channel_restriction_type'] = reqData['channel_restriction_type'];
          formData['channel_ids'] = reqData['channel_ids'];

          apiAdvertisingCreate(formData)
            .then((response) => {
              _this.loading_end("form");
              _this.$message({
                message: response.msg,
                type: "success",
              });
              _this.$router.go(-1);
            })
            .catch(function (result) {
              _this.$message.error(result.msg);
            });
        }
      });
    },
    // 获取详情
    req_details(id) {
      const _this = this;
      _this.loading_start("form");
      if (!id) {
        return;
      }
      apiAdvertisingDetails({
        id: id,
      })
        .then((response) => {
          const result = response.data.details;
          var form = result;
          form.time_interval = [
            parseMmDdDate(result.today_start_time),
            parseMmDdDate(result.today_end_time),
          ];
          // form = assignFormParams(_this.form, form);
          if(form['channel_ids']){
            form['channel_ids'] = JSON.parse(form['channel_ids']);
          }
          _this.form = form;
          _this.loading_end("form");
        })
        .catch(function (result) {
          console.error(result, 'result')
          _this.$message.error(result.msg);
          _this.loading_end("form");
        });
    },

    // 加载开始...
    loading_start(keys) {
      if (Array.isArray(keys)) {
        keys.forEach((key) => {
          this.loading[key] = true;
          setTimeout(() => {
            this.loading[key] = false;
          }, 5000);
        });
      } else {
        this.loading[keys] = true;
        setTimeout(() => {
          this.loading[keys] = false;
        }, 5000);
      }
    },
    // 加载结束...
    loading_end(keys) {
      if (Array.isArray(keys)) {
        keys.forEach((key) => {
          this.loading[key] = false;
        });
      } else {
        this.loading[keys] = false;
      }
    },
  },
};
</script>

<style lang="scss"></style>